<?php
/***************
* @Project	Warabi
* @Author	Feifei
* @Date		04/11/2009
***************/

/**This module is to deal the ap get card invitation state**/

include_once($_SERVER['DOCUMENT_ROOT'].'/header.inc.php');

$httprequest = new wbHttpRequest();

list($headers , $body) = $httprequest->output();

$sender_name= rawurldecode($_GET["sender"]);
$receiver_name = rawurldecode($_GET["usr"]);
$card_id = rawurldecode($_GET["id"]);

/***if the sender name is empty or receiver_name and card id is empty**/
if(empty($sender_name) || (empty($receiver_name) && empty($card_id))){
	header(error_url_param_missing);
	exit;
}

/**if the sender doesn't exist in database , give a 400 response**/
$db = new wbDatabase();
$sql = "select * from ".__table_app_user__." where username='".$sender_name."'";
$set = $db->query($sql);

if($db->countResult($set)==0){
	header(error_url_param_missing);
	exit;
}

$db->freeResult($set);

/** wsse authorize **/
/***if the wsse is wrong , give a 401 unauthorized response**/
$xwsse = $headers["X_WSSE"];
$type=0;
$doorkey = magicWsse($xwsse , $db , $type);

if(!$doorkey){
	header(error_autorized_header);
	exit;
}


/** if provide the sender name and the receiver_name|card_id**/
$where = empty($receiver_name)? " cardListId = '".$card_id."'" : " receiver = '".$receiver_name."'";
$expireFlag = " sendDate<(date_sub(now(),interval ".(expire_time." ".expire_unit).")) as expireFlag";
$sql = "select *, ".$expireFlag." from ".__table_card_info__." , ".__table_card_list__."
			where ".__table_card_info__.".id = ".__table_card_list__.".cardInfoId
			and ".__table_card_info__.".sender = '".$sender_name."' 
			and ".$where;

$set = $db->query($sql);
$result = array();
while($oneres = $db->fetchResultBySet($set , MYSQL_ASSOC)){
	$tmparr = array(
		"sender" => $oneres["sender"],
		"description" => $oneres["description"],
		"date" => $oneres["sendDate"],
		"photo" => $oneres["photoNumber"],
		"flag" => getInviteFlag($oneres["deleteFlag"],$oneres["expireFlag"],$oneres["readFlag"]),
		"id" => $oneres["cardListId"]
	);
	$result[] = $tmparr;
}
$db->freeResult($set);
$db->disconnect();

/***put the response to the client**/
$tid = getTid();
$resBody = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
$resBody .= "<entry>";
$resBody .= "<tid>".$tid."</tid>";
foreach($result as $stat){
	$resBody .= "<invite>";
	$resBody .= "<sender>".$stat["sender"]."</sender>";
	$resBody .="<description>".$stat["description"]."</description>";
	$resBody .="<date>".$stat["date"]."</date>";
	$resBody .="<photo>".$stat["photo"]."</photo>";
	$resBody .="<flag>".$stat["flag"]."</flag>";
	$resBody .="<id>".$stat["id"]."</id>";
	$resBody .= "</invite>";
}
$resBody .= "</entry>";

header(success_response);
header('Content-Type: text/xml');
header('Content-Length: '.strlen($resBody));
echo $resBody;

?>
